package cn.stylefeng.guns.modular.basic.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicCostStandardConf;
import cn.stylefeng.guns.modular.basic.mapper.BasicCostStandardConfMapper;
import cn.stylefeng.guns.modular.basic.model.params.BasicCostStandardConfParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicCostStandardConfResult;
import cn.stylefeng.guns.modular.basic.service.BasicCostStandardConfService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 成本标准配置表 服务实现类
 * </p>
 *
 * @author zhangzh
 * @since 2024-05-08
 */
@Service
public class BasicCostStandardConfServiceImpl extends ServiceImpl<BasicCostStandardConfMapper, BasicCostStandardConf> implements BasicCostStandardConfService {

    @Override
    public void add(BasicCostStandardConfParam param) {
        BasicCostStandardConf entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BasicCostStandardConfParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(BasicCostStandardConfParam param) {
        BasicCostStandardConf oldEntity = getOldEntity(param);
        BasicCostStandardConf newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BasicCostStandardConfResult findBySpec(BasicCostStandardConfParam param) {
        return null;
    }

    @Override
    public List<BasicCostStandardConfResult> findListBySpec(BasicCostStandardConfParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BasicCostStandardConfParam param, String condition) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param, condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<BasicCostStandardConfResult> findAll(BasicCostStandardConfParam param, String condition) {
        return this.baseMapper.customAllList(param, condition);
    }

    private Serializable getKey(BasicCostStandardConfParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BasicCostStandardConf getOldEntity(BasicCostStandardConfParam param) {
        return this.getById(getKey(param));
    }

    private BasicCostStandardConf getEntity(BasicCostStandardConfParam param) {
        BasicCostStandardConf entity = new BasicCostStandardConf();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 150)
    public ResponseData getExceldata(@NotNull MultipartFile file, BasicCostStandardConfParam basicCostStandardConfParam, ResponseData data) throws Exception {
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        //根据部门ID删除记录
        this.baseMapper.delByProId(basicCostStandardConfParam.getProId());

        List<BasicCostStandardConfParam> list = new ArrayList<BasicCostStandardConfParam>();
        BasicCostStandardConfParam basicCostStandardConfVo = null;
        for (int r = 1; r <= sheet.getLastRowNum() + 1; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //实体类
            basicCostStandardConfVo = new BasicCostStandardConfParam();
            //交付客户
            basicCostStandardConfVo.setDeliverId(basicCostStandardConfParam.getDeliverId());
            //部门
            basicCostStandardConfVo.setDeptId(basicCostStandardConfParam.getDeptId());
            //创建时间
            basicCostStandardConfVo.setCreateTime(basicCostStandardConfParam.getCreateTime());
            //创建人
            basicCostStandardConfVo.setCreateUser(basicCostStandardConfParam.getCreateUser());
            //修改人
            basicCostStandardConfVo.setUpdateUser(basicCostStandardConfParam.getUpdateUser());
            //项目
            basicCostStandardConfVo.setProId(basicCostStandardConfParam.getProId());
            // 车限类型  重量 ；体积
            String vehLimitTyp = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(vehLimitTyp)) {
                basicCostStandardConfVo.setVehLimitTyp(vehLimitTyp);
            }
            // 车限类型区间最小值
            String vehLimitMin = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(vehLimitTyp)) {
                basicCostStandardConfVo.setVehLimitMin(new BigDecimal(vehLimitMin));
            }
            // 车限类型区间最大值
            String vehLimitMax = getCellValue(row.getCell(2));
            if (ToolUtil.isNotEmpty(vehLimitTyp)) {
                basicCostStandardConfVo.setVehLimitMax(new BigDecimal(vehLimitMax));
            }
            // 公里区间最小值
            String kiloRangeMin = getCellValue(row.getCell(3));
            if (ToolUtil.isNotEmpty(vehLimitTyp)) {
                basicCostStandardConfVo.setKiloRangeMin(new BigDecimal(kiloRangeMin));
            }
            // 公里区间最大值
            String kiloRangeMax = getCellValue(row.getCell(4));
            if (ToolUtil.isNotEmpty(vehLimitTyp)) {
                basicCostStandardConfVo.setKiloRangeMax(new BigDecimal(kiloRangeMax));
            }
            // 单价
            String price = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(vehLimitTyp)) {
                basicCostStandardConfVo.setPrice(new BigDecimal(price));
            }

            // 序号
            String odr = getCellValue(row.getCell(6));
            if (ToolUtil.isNotEmpty(vehLimitTyp)) {
                basicCostStandardConfVo.setOdr(Integer.valueOf(odr));
            }

            list.add(basicCostStandardConfVo);
        }
        //批量保存
        this.baseMapper.saveBatchList(list);

        data.setSuccess(true);
        return data;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

}